﻿using System.ComponentModel.Composition;
using System.ServiceModel;
using System.Windows.Input;
using Microsoft.Practices.Prism.Commands;
using YunBox2.Contracts;
using YunBox2.Contracts.Core;

namespace YunBox2.Client.Infrastructure.ViewModels
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MyEmailEditorViewModel : DomainObject
    {
        private readonly DelegateCommand _changeEmailCommand;
        private readonly ISystemService _systemService = ClientContext.Current.SystemService;
        private string _email;

        [ImportingConstructor]
        public MyEmailEditorViewModel()
        {
            _email = ClientContext.Current.CurrentUser.Email;

            _changeEmailCommand = new DelegateCommand(ChangeEmail);
            _resetCommand=new DelegateCommand(Reset);
        }

        public ICommand ChangeEmailCommand
        {
            get
            {
                return _changeEmailCommand;
            }
        }

        public string Email
        {
            get
            {
                return _email;
            }
            set
            {
                if (_email != value)
                {
                    _email = value;
                    RaisePropertyChanged("Email");
                }
            }
        }

        private void ChangeEmail()
        {
            using (OperationContextScope cs = ClientContext.Current.CreateOperationContextScope(_systemService as IContextChannel))
            {
                if (_systemService.ChangeMyEmail(Email))
                {
                    ClientContext.Current.CurrentUser = _systemService.GetMyProfile();
                }
            }
        }

        private void Reset()
        {
            Email = ClientContext.Current.CurrentUser.Email;
        }

        private DelegateCommand _resetCommand;
        public ICommand ResetCommand
        {
            get
            {
                return _resetCommand;
            }
        }
    }
}